package jjn.carl.array;

import java.util.Arrays;

/**
 * @author Jiang Jining
 * @since 2023-06-29 22:06
 */
public class LeetCode977 {
    
    public int[] sortedSquares(int[] nums) {
        // 双指针解法，题目中的
        int left = 0, right = nums.length - 1;
        int[] result = new int[nums.length];
        int start = right;
        // 结束条件, left == right
        while (left <= right) {
            // 按要求分别计算左边和右边的平方值
            int leftSquare = nums[left] * nums[left];
            int rightSquare = nums[right] * nums[right];
            if (leftSquare >= rightSquare) {
                result[start] = leftSquare;
                left++;
            } else {
                result[start] = rightSquare;
                right--;
            }
            start--;
        }
        return result;
    }
    
    public static void main(String[] args) {
        int[] nums = new int[]{-4, -1, 0, 3, 10};
        int[] result = new LeetCode977().sortedSquares(nums);
        System.out.println("result = " + Arrays.toString(result));
    }
}
